<% content_for (:head)  do %>
   <title>Noisetube | Query</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=drawing&sensor=true"></script>
    <script type="text/javascript" src="/assets/distgeo.js"></script>

   <script type="text/javascript">

       //the map
       var map;
       var infowindow = new google.maps.InfoWindow({content: "<div class = '.infowindow'><i>Loading...</i></div>"});
       var markers = [];
       var MAX_DISTANCE = 4.4;
       var MIN_ZOOM_LEVEL = 13;
       //google maps recommends array for all overlays
       var overlays = [];

       $(document).ready(function() {
           $("#track_id").multiselect();
           $("#user_id").multiselect();

           $('#starttime').datetimepicker();
           $('#endtime').datetimepicker();

           $( "#db-range" ).slider({
               range: true,
               min: 25,
               max: 120,
               values: [25,120],
               slide: function( event, ui ) {
                   $( "#dbstart" ).val( ui.values[ 0 ]);
                   $( "#dbend" ).val( ui.values[ 1 ]);
               }
           });
            //set the btn clicked to store in theaction hidden field
           $(":submit").click(function () { $("#theaction").val(this.id); });

           /*
           *   loadMeasuresOnMap - load measurements as markers onto the map
           */
           var loadMeasuresOnMap = function(result){
               //remove markers
               if(markers && markers.length !== 0){
                   for(var i = 0; i < markers.length; ++i){
                       markers[i].setMap(null);
                   }
               }
               var bounds = new google.maps.LatLngBounds ();

               $.each(result, function(index, item){
                   if (item.measures){
                       $.each(item.measures, function(midx, measure){
                           var marker = addMarker(map, "Measurement", measure.id, measure.lat, measure.lng, item.user.login, measure);

                           // create for extending bounds
                           var latlng = new google.maps.LatLng(measure.lat, measure.lng);

                           // increase the bounds to take this point
                           bounds.extend (latlng);
                           markers.push(marker);
                       });
                       if (item.measures.length > 0) map.fitBounds (bounds);

                   }
               });

           };

           var addMarker = function (map, infotitle, measure_id, lat, lng, userlogin, measure) {
               var myLatlng = new google.maps.LatLng(lat, lng);
               var marker = new google.maps.Marker({position: myLatlng, map: map, title:infotitle});

               google.maps.event.addListener(marker, 'click', function() {
                   //test
                   infowindow.close();
                   $.getJSON("/ajax/measureinfo?mid=" + measure_id, function(data){

                       //format the string
                       var text = "";
                       var measureTag = "<b><%= t 'cities.iscope.measure' %></b>";
                       var loudnessTag = "<b><%= t 'cities.iscope.loudness' %></b>";
                       var madeAtTag = "<b><%= t 'cities.iscope.madeAt' %></b>";
                       var madebyTag = "<b><%= t 'cities.iscope.madeBy' %></b>";
                       var coordinatesTag = "<b><%= t 'cities.iscope.coords' %></b>";

                       text += "<h3>"+measureTag+"</h3>";
                       text += "<p>"+loudnessTag+": "+measure.loudness +"<br/>";
                       text += madeAtTag+ " "+ measure.made_at+"<br/>";
                       text += coordinatesTag+ " (lat:"+ measure.lat.toFixed(5)+", lng: "+measure.lng.toFixed(5)+")<br/>";
                       text += madebyTag+ " "+ userlogin;
                       text += "</p>";
                      //text += "id: "+ measure.id;
                       //set leq_image for the city
                       infowindow.setContent(text);
                       infowindow.open(map, marker);

                   });

               });
               return marker;
           };

           //ajax
           //load the map's measures on click
           $("#queryform").submit(function(e) {
               //get the data as json
               data = $('#queryform').serialize();
               var url = "/cities/runquery";

               var usrid = $('#user_id').val();
               //show dialog for bbox validation
               if (!usrid){
                   $( "#dialog-message" ).dialog({
                       modal: true,
                       buttons: {
                           Ok: function() {
                               $( this ).dialog( "close" );
                           }
                       }
                   });
                   e.preventDefault();
                   //dont submit
                   return;
               }

               var task = $('#theaction').val();
               //can check theaction here to determine action
               if ( task === "btnsubmitmap"){
                   //show on map
                   e.preventDefault();

                   //show wait gigf
                   $('#wait').show();
                   $('#form-buttons').hide();
                   //then show on map
                   var posting = $.post( url, data).done(function(data) {
                       $('#wait').hide();
                       $('#form-buttons').show();
                       if (data){

                           //load the map
                           loadMeasuresOnMap(data);

                           //focus map
                           $('html, body').animate({ scrollTop: $('#map-div').offset().top }, 'slow');
                       }
                       else {
                           $('#results').text("No data found for query. ");
                       }
                   });

               } else if (task === "btnsubmit"){


                   //get the parent id
                   var parent_id = $(this).attr("id");

                   var posting = $.post( url, data).done(function(data) {
                       if (!data){
                           $('#results').text("No data found for query. ");
                       }
                   });
               } else if (task === "btnaggmap"){
                   var aggurl = "/cities/aggmap";
                   //show on map
                   e.preventDefault();

                   //wait gif
                   $('#wait').show();
                   $('#form-buttons').hide();
                   //then show on map
                   $.post( aggurl, data).done(function(result) {
                       $('#wait').hide();
                       $('#form-buttons').show();
                       if (result){

                           //load the map
                           loadAggregatedMap(result);

                           //focus map
                           $('html, body').animate({ scrollTop: $('#map-div').offset().top }, 'slow');
                       }
                       else {
                           $('#results').text("No data found. ");
                       }
                   });

               }

           });
           //load the map
            initializeMap('map-div');
       });

       /*
        *  function initializeMap - id is the id for the elm
        */
       function initializeMap(id) {

           var usrLat, usrLng;
           //default client location
           // Try W3C Geolocation
           if(navigator.geolocation) {
               navigator.geolocation.getCurrentPosition(function(position) {
                   var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
                   usrLat = initialLocation.lat();
                   usrLng = initialLocation.lng();
                   //change map center
                   if (map) map.setCenter(initialLocation);
               }, function() {
                   console.info("User location not detected.");
               });
           }
           // Browser doesn't support Geolocation
           else {
               console.info("User location not detected. Browser does not support this feature.");
           }

           var mapOptions = {
               center: new google.maps.LatLng(usrLat || 50.8, usrLng || 4.34),
               zoom: MIN_ZOOM_LEVEL,
               mapTypeId: google.maps.MapTypeId.ROADMAP
           };
           map = new google.maps.Map(document.getElementById(id),
                   mapOptions);

           var drawingManager = new google.maps.drawing.DrawingManager({
               drawingMode: google.maps.drawing.OverlayType.RECTANGLE,
               drawingControl: true,
               drawingControlOptions: {
                   position: google.maps.ControlPosition.TOP_CENTER,
                   drawingModes: [
                       //google.maps.drawing.OverlayType.MARKER,
                       google.maps.drawing.OverlayType.RECTANGLE
                   ]
               }
           });
           drawingManager.setMap(map);

           //add draw rectevent listener

           google.maps.event.addDomListener(drawingManager, 'rectanglecomplete', function(rectangle) {

               //only one shape, disable controls
                drawingManager.setOptions({
                    drawingMode: null//,
                    //drawingControl: false
                });

               //editable, draggable
               rectangle.setOptions({editable: true, draggable: true});

               function setBounds(rectangle) {
                   //get the rectangle bounds, set to controls
                   var tlLng =  rectangle.getBounds().getNorthEast().lng();
                   var tlLat =  rectangle.getBounds().getSouthWest().lat();

                   var brLat =  rectangle.getBounds().getNorthEast().lat();
                   var brLng =  rectangle.getBounds().getSouthWest().lng();

                   //disable if distance on diagonal > 4.3 kms
                   var p1 = new LatLon(tlLat,tlLng);
                   var p2 = new LatLon(brLat,brLng);
                   var dist = p1.distanceTo(p2);
                   //get the bearing
                   var bearing = p1.bearingTo(p2);

                   console.log("distance of bounds: "+dist);
                   if (dist > MAX_DISTANCE){
                       var pMax = p1.destinationPoint(bearing, dist);
                      //rectangle.setBounds(new google.maps.LatLngBounds( new google.maps.LatLng(tlLat,pMax.lon()), new google.maps.LatLng(pMax.lat(), tlLng)) );
                   }

                  // if (dist) > 4.3
                   $('#geotl').val(tlLat.toFixed(6) + ", " +tlLng.toFixed(6) );
                   $('#geobr').val(brLat.toFixed(6) + ", " + brLng.toFixed(6));
               }
               //set bounds after drawing
               setBounds(rectangle);

               //set bounds if resized
               google.maps.event.addListener(rectangle, "bounds_changed", function() {

                   setBounds(rectangle);

               });

               //add rectangle to array
               overlays.push(rectangle);
           });

       }

   function loadAggregatedMap(data){
       //coloring for the average values of the regions
       var noisecolor = function(n)
       {
           if (!n)
               return '';

           n = Number(n);

           if (n<35)
               return  '#72c117';
           if (n>=35 && n<40)
               return  '#72c117';
           if (n>=40 && n<45)
               return  '#72c117';
           if (n>=45 && n<50)
               return  '#72c117';
           if (n>=50 && n<55)
               return  '#72c117';
           if (n>=55 && n<60)
               return  '#c6c605';
           if (n>=60 && n<65)
               return  '#FCB061';
           if (n>=65 && n<70)
               return  '#FC8107';
           if (n>=70 && n<75)
               return  '#FC4D4D';
           if (n>=75 && n<80)
               return  '#EC0102';
           if (n>80)
               return  '#990000';
           return '#8BB381';
       };
       //remove overlays
       while(overlays[0]){
           overlays.pop().setMap(null);
       }
       //each array entry has grid coords, measures and stats
       data.forEach(function(item){
           //if (item.count > 0){   //skips empty grids
               //create the boxes as overlays
               var points = [
                   new google.maps.LatLng(item.xmin, item.ymin),
                   new google.maps.LatLng(item.xmax, item.ymin),
                   new google.maps.LatLng(item.xmax, item.ymax),
                   new google.maps.LatLng(item.xmin, item.ymax)

               ];

               var poly = new google.maps.Polygon({
                   paths: points,
                   strokeColor: noisecolor(item.mean),
                   strokeOpacity: 0.8,
                   strokeWeight: 2,
                   fillColor: noisecolor(item.mean),	//"#FF0000",
                   fillOpacity: 0.35
               });

               // Add a listener for the click event
               google.maps.event.addListener(poly, 'click', function(evt){
                    //add info window then add to map
                   var sumtag = "<b><%= t 'cities.infowindow.sum' %>: </b>";
                   var meantag = "<b><%= t 'cities.infowindow.mean' %>: </b>";
                   var variancetag = "<b><%= t 'cities.infowindow.variance' %>: </b>";
                   var stdevtag = "<b><%= t 'cities.infowindow.stdev' %>: </b>";
                   var counttag = "<b><%= t 'cities.infowindow.count' %>: </b>";
                   var text = "<h3><%= t 'cities.infowindow.measurementsgrid' %></h3>";

                   //text += sumtag + item.sum + "<br/>";
                   text += meantag + item.mean + "<br/>";
                   text += variancetag + item.variance + "<br/>";
                   text += stdevtag + item.stdev + "<br/>";
                   text += counttag + item.count + "<br/>";
                    infowindow.setContent(text);
                    infowindow.setPosition(evt.latLng);
                    infowindow.open(map);
               });

               poly.setMap(map);
               overlays.push(poly);
           //}

       });
   }

   </script>
<% end %>

<% if flash[:error] %>
    <div style="color: #a11328;" class="error"><%= flash[:error] %></div>
<% end %>
<div id="page">
  <% if flash[:alert] %>
      <p class="flash-error"><%= flash[:alert] %></p>
  <% end %>
  <% if flash[:notice] %>
      <p class="flash-notice"><%= flash[:notice] %></p>
  <% end %>
</div>

<div class="intro">
  <h3><%= (t 'cities.iscope.queryinfobox.title' ) << ": "<< @city.name %></h3>
  <p><%= t 'cities.iscope.queryinfobox.desc' %></p>

</div>
<br />

<div id="map-div" style="width: 100%; height: 400px;">
</div>

<br />
<div>
<p>
  <%= form_tag "/cities/runquery", id: "queryform"  do %>
     <!-- TODO: add validation - must select at least one user -->
    <%= label_tag("user", (t "cities.iscope.selectusers")) %>
    <%= collection_select :user, :id, @city_track_users, :id, :login, {}, {:multiple => true, :style => "width: 300px;"} %>

      <% #label_tag("track", (t "cities.iscope.selecttrack")) %>
      <% #collection_select :track, :id, @city_tracks, :id, :created_at, {}, {:multiple => true, :style => "width: 300px;"} %>
      <br /><br />
      <%= label_tag("geotl", (t "cities.iscope.boundingboxtl")) %>
      <%= text_field_tag 'geotl', nil, :placeholder => 'lat, lng',  :class => 'form_text_field_latlng' %>
      <br /><br />
      <%= label_tag("geobr", (t "cities.iscope.boundingboxbr")) %>
      <%= text_field_tag 'geobr', nil, :placeholder => 'lat, lng', :class => 'form_text_field_latlng' %>
      <br /><br />
      <%= label_tag("starttime", (t "cities.iscope.starttime")) %>
      <%= text_field_tag 'starttime', nil, :class => 'form_text_field'%>
      <br /><br />
      <%= label_tag("endtime", (t "cities.iscope.endtime")) %>
      <%= text_field_tag 'endtime', nil, :class => 'form_text_field'%>
      <br /><br />

      <input type="hidden" name="theaction" id="theaction" />

       <div style="margin-bottom: 5px;"> <%=  t 'cities.iscope.loudness' %>  </div>
        <div id="db-range" style="width: 480px; margin-bottom: 10px;"></div>
        <%= label_tag("dbstart", (t "cities.iscope.dbstart")) %>
      <%= text_field_tag 'dbstart', nil, :class => 'form_text_field'%>
      <%= label_tag("dbend", (t "cities.iscope.dbend")) %>
      <%= text_field_tag 'dbend', nil, :class => 'form_text_field'%>
      <br /><br />
      <%=  image_tag("/images/icons/spinner.gif", :class => "loading-icon", :id=> "wait") %>
      <div id="form-buttons">
        <%=  submit_tag (t "cities.iscope.viewresultasjson"), {id: "btnsubmit"} %>
        <%=  submit_tag (t "cities.iscope.viewresultonmap"), {id: "btnsubmitmap"} %>
        <%=  submit_tag (t "cities.iscope.viewaggregatedmap"), {id: "btnaggmap"} %>
      </div>

<% end %>
</p>
</div>

<div id="results">


</div>

<div id="dialog-message" title="<%= t 'cities.iscope.aggmaps.selectauser' %>" style="display:none;">
  <br />
  <p>
    <span class="ui-icon ui-icon-circle-check" style="float: left; margin: 0 7px 10px 0;"></span>
    <%= t 'cities.iscope.aggmaps.selectuserfirst' %>
  </p>
</div>